//
//  RegisterPayVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/3/16.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "RegisterPayVC.h"
#import "RegisterPaySuccessVC.h"
#import "BaseTabBarController.h"

extern UserModel *userModel;
@interface RegisterPayVC ()
@property (weak, nonatomic) IBOutlet WRBaseButton *confirmBtn;
@property (weak, nonatomic) IBOutlet UIButton *zfbBtn;
@property (weak, nonatomic) IBOutlet UIButton *wxBtn;

@property (nonatomic, assign) BOOL isWx;
@property (strong, nonatomic)NSString *order_code;
@end

@implementation RegisterPayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.title = @"支付";
    [self setUi];
}

- (void)setUi {
    
    
    if (NeediPhoneXiPhoneXR) {
        self.top.constant = NEW_StatusBarHeight;
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noticePaySuccess) name:NoticePaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noticePayFailure) name:NoticePayFailure object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noticePayCancel) name:NoticePayCancel object:nil];
    
    [self requestDataTwo];
    if ([CommonTTool isStrNull:self.access_token]) {
        self.access_token = [LEUserManager token];
    }
    
    
}

- (void)requestDataTwo {
        
    int type = 0;
    if (self.orderType == 0) {
        type = 9;
        
    }
    if (self.orderType == 1) {
        type = 3;
    }
    if (self.orderType == 2) {
        type = 10;
    }
    
    [NetRequestTool postUrl:@"sysCode/querySysCodeObject" parameters:@{@"type":@(type)} success:^(id responseObject) {
        NSString *str = [NSString stringWithFormat:@"您需要支付￥%@元",responseObject[@"object"][@"value"]];
        self.payLabel.text = str;

    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
    
}


- (void)noticePaySuccess {
    
    
    [NetRequestTool noTokenPostUrl:@"user/getUserInfo" parameters:@{@"access_token":self.access_token} success:^(id responseObject) {
        NSDictionary *dic = responseObject[@"object"];
        [[NSUserDefaults standardUserDefaults] setObject:[dic deleteNull] forKey:kUserInfo];
        userModel = [UserModel mj_objectWithKeyValues:dic];
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        
    }];
    
//    [NetRequestTool postUrl:@"user/getUserInfo" parameters:@{} success:^(id responseObject) {
//
//        NSDictionary *dic = responseObject[@"object"];
//        [[NSUserDefaults standardUserDefaults] setObject:[dic deleteNull] forKey:kUserInfo];
//        userModel = [UserModel mj_objectWithKeyValues:dic];
//
//    } failure:^(NSInteger statusCode) {
//
//    } finish:^{
//        SVPDismiss
//    }];
    
    
    if (self.type == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        RegisterPaySuccessVC *vc = [[RegisterPaySuccessVC alloc]initWithNibName:@"RegisterPaySuccessVC" bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
   
    
    
}

- (void)noticePayFailure {
    if (self.type == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
//        [self.navigationController popToRootViewControllerAnimated:YES];
        [self Login];
    }
    
    
    
    
}

- (void)noticePayCancel {
    
    SVP(@"已取消支付");
    [self Login];

}

-  (void)back {
    if ([CommonTTool isStrNull:self.username]) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    [self Login];
}

- (void)Login {
    
    if ([CommonTTool isStrNull:self.username]) {
        
        return;
    }
    
    [NetManager isLoginWithParameters:@{@"username":self.username,@"password":self.password} success:^{
        
        SVP(@"登录成功");
        dispatch_async(dispatch_get_main_queue(), ^{
            // 记录是否是商户
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"kUserIsMerchants"];
            
            BaseTabBarController *baseTabBar = [[BaseTabBarController alloc]init];
            AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
            baseTabBar.selectedIndex = 0;
            delegate.window.rootViewController = baseTabBar;
        });
        
        
    }];
}

- (void)orderSave {
    
    NSString *pay_type = @"";
    
    if (self.isWx) {
        pay_type = @"2";
    }else {
        pay_type = @"1";
    }
    if (self.access_token == nil) {
        self.access_token = [LEUserManager token];
    }
    
    
    NSDictionary *para = @{@"type":@(self.orderType),
                           @"pay_type":pay_type,
                            @"access_token":self.access_token
    };
    
    SVPShowInternetWaiting
    [NetRequestTool noTokenPostUrl:@"order/saveOrder" parameters:para success:^(id responseObject) {
        
        self.order_code = responseObject[@"object"];

        if (self.isWx) {

            [self getWXPay];

        }else {

            [self getZFBPay];

        }
        
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
            
    }];
    
//    SVPShowInternetWaiting
//    [NetManager isOrderSaveOrderParameters:para success:^(NSDictionary * _Nonnull dic) {
//
//        self.order_code = dic[@"object"];
//
//        if (self.isWx) {
//
//            [self getWXPay];
//
//        }else {
//
//            [self getZFBPay];
//
//        }
//
//    } finish:^{
//
//    }];
    
    
}


- (void)getZFBPay {
    
    SVPShowInternetWaiting
    [NetRequestTool noTokenPostUrl:@"pay/getAliPayInfo" parameters:@{@"order_code":self.order_code,@"access_token":self.access_token} success:^(id responseObject) {
        NSString *appScheme = @"woweirenren";

        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:responseObject[@"object"] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
           NSLog(@"reslut = %@",resultDic);
        }];
        
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
            
    }];
    
//    [NetManager isGetAliPayInfoParameters:@{@"order_code":self.order_code,@"access_token":self.access_token} success:^(NSDictionary * _Nonnull dic) {
//        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
//        NSString *appScheme = @"woweirenren";
//
//        // NOTE: 调用支付结果开始支付
//        [[AlipaySDK defaultService] payOrder:dic[@"object"] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//            NSLog(@"reslut = %@",resultDic);
//        }];
//
//    } finish:^{
//
//    }];
    
}

- (void)getWXPay {
    
    
    SVPShowInternetWaiting
    SVPShowInternetWaiting
    [NetRequestTool noTokenPostUrl:@"pay/getPreReqParamsModel" parameters:@{@"order_code":self.order_code,@"t":@"APP", @"access_token":self.access_token} success:^(id responseObject) {
        
        NSDictionary *dict = responseObject[@"object"];
        
        PayReq* req = [[PayReq alloc] init];
        req.partnerId   = dict[@"partnerid"];
        req.prepayId    = dict[@"prepayid"];
        req.nonceStr    = dict[@"nonceStr"];
        UInt32 num;
        sscanf([dict[@"timeStamp"] UTF8String], "%u", &num);
        req.timeStamp = num;
        req.package     = dict[@"packageStr"];
        req.sign = dict[@"paySign"];
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
            
    }];
    
    
//    [NetManager isGetPreReqParamsModelParameters:@{@"order_code":self.order_code,@"t":@"APP", @"access_token":self.access_token} success:^(NSDictionary * _Nonnull dic) {
//        NSDictionary *dict = dic[@"object"];
//
//        PayReq* req = [[PayReq alloc] init];
//        req.partnerId   = dict[@"partnerid"];
//        req.prepayId    = dict[@"prepayid"];
//        req.nonceStr    = dict[@"nonceStr"];
//        UInt32 num;
//        sscanf([dict[@"timeStamp"] UTF8String], "%u", &num);
//        req.timeStamp = num;
//        req.package     = dict[@"packageStr"];
//        req.sign = dict[@"paySign"];
//        [WXApi sendReq:req];
//
//    } finish:^{
//
//    }];
    
}


//- (void)back {
//
//
//    UIAlertController *alterController2 = [UIAlertController alertControllerWithTitle:nil message:@"是否确定放弃支付开通会员？" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"狠心放弃" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        if (self.type == 1) {
//            [self.navigationController popViewControllerAnimated:YES];
//        }else {
//            [self.navigationController popToRootViewControllerAnimated:YES];
//        }
//
//    }];
//
//    UIAlertAction *answerAction = [UIAlertAction actionWithTitle:@"再想想" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//    }];
//    [alterController2 addAction:cancelAction];
//    [alterController2 addAction:answerAction];
//
//    [self presentViewController:alterController2 animated:YES completion:nil];
//
//
//
//}


- (IBAction)nextBtnClcil:(id)sender {
    
    
    
    [self orderSave];
    
    
}




- (IBAction)zfbClick:(id)sender {
    
    
    self.zfbBtn.selected = YES;
    self.wxBtn.selected = NO;
    self.isWx = NO;
    
    
}
- (IBAction)wxClick:(id)sender {
    
    self.zfbBtn.selected = NO;
    self.wxBtn.selected = YES;
    self.isWx = YES;
    
}

@end
